#!/usr/bin/python3


from log import *

import cx_Oracle


class COracleDB:
    def __init__(self, log, dbHost="10.1.54.50", dbPort=1521,
                 dbUser="shengli", dbPwd="shengli0",
                 dbName="orcl"):
        self.log = log
        self.dbHost = dbHost
        self.dbPort = dbPort
        self.dbUser = dbUser
        self.dbUserPwd = dbPwd
        self.dbName = dbName

    def init(self):
        try:
            self.DB = cx_Oracle.connect(self.dbUser + "/" +self.dbUserPwd +
                                        "@//" + self.dbHost+":"+str(self.dbPort)+"/" + self.dbName)
            self.cursor = self.DB.cursor()
            self.log.log("connect to oracle database :" + self.dbHost + ":" + str(self.dbPort) + ":" +self.dbName)
        except cx_Oracle.Error as e:
            self.log.log("connect to oracle database fialed:" + self.dbHost + ":" + str(self.dbPort), error)
            return e

    def close(self):
        try:
            self.cursor.close()
            self.DB.close()
        except:
            return

    def query(self, queryStr):
        try:
            self.log.log("oracle query, sql:" + queryStr)
            self.cursor.execute(queryStr)
        except cx_Oracle.DatabaseError as e:
            self.log.log("oracle query failed, error:" + queryStr + str(e))
            return e

    def exec(self, execStr, tableName):
        try:
            self.DB.cursor.execute("lock table " + tableName + " in row share mode wait 10;")
            self.log.log("oracle exec, sql:" + execStr)
            self.cursor.execute(execStr)
            self.DB.commit()

        except cx_Oracle.DatabaseError as e:
            self.DB.rollback()
            self.log.log("oracle exec failed, rollback, sql:" + execStr + " error:" + str(e), error)
            return e


    def getData(self):
        try:
            rows = self.cursor.fetchall()
            return rows
        except cx_Oracle.Error as e:
            self.log.log("oracle get data failed, error:" + str(e))

            return e







#已测试
#testLog = CLog(logName="test.log", isPrint=True)
#
#testDB = COracleDB(log=testLog, dbHost="10.1.54.50", dbUser="shengli", dbPwd="shengli0", dbName="orcl")
#testDB.init()
#
#testDB.query(queryStr="select * from t_user")
#data = testDB.getData()
#print(data)
#
#testDB.exec(execStr="update t_user set pwd = '2' where user_name = 'admin'")
##testDB.query(sqlStr="select * from t_user")
#data = testDB.getData()
#print(data)
#
#userInfo = { "userName" : ["pwd", "", "", "", "", ""]}
#for row in data:
#    userInfo[row[0] ] = [row[1], row[2], row[3], row[4], row[5], row[6] ]
#
#print (userInfo)



